﻿using GammaJul.ReSharper.GammaXaml.Highlightings.Xaml;
using GammaJul.ReSharper.GammaXaml.Psi.Xaml;
using JetBrains.Annotations;
using JetBrains.ReSharper.Daemon;
using JetBrains.ReSharper.Daemon.Stages;
using JetBrains.ReSharper.Psi.Resolve;
using JetBrains.ReSharper.Psi.Tree;
using JetBrains.ReSharper.Psi.Xaml.Impl.Tree;
using JetBrains.ReSharper.Psi.Xaml.Tree;
using JetBrains.ReSharper.Psi.Xaml.Tree.MarkupExtensions;

namespace GammaJul.ReSharper.GammaXaml.Analysis.Xaml {

	/// <summary>
	/// Analyzer that checks that a ElementName binding is resolved correctly.
	/// </summary>
	public class UnresolvedElementNameAnalysis : XamlAnalysis {

		public override void ProcessBeforeInterior(ITreeNode element, IHighlightingConsumer highlightings) {
			var usage = element as IElementNameUsage;
			if (usage == null)
				return;

			var nameRef = usage.ElementNameReference;
			if (nameRef == null || nameRef.Resolve().ResolveErrorType == ResolveErrorType.OK)
				return;

			ITreeNode valueNode = GetValueNode(usage);
			if (valueNode == null)
				return;

			highlightings.AddHighlighting(new ElementNameNotResolvedHighlighting(nameRef), valueNode.GetHighlightingRange(), XamlFile);
		}

		[CanBeNull]
		private static ITreeNode GetValueNode([CanBeNull] IElementNameUsage usage) {
			var propSetter = usage as IPropertySetter;
			if (propSetter != null)
				return propSetter.GetValueToken();
			
			var markupAttr = usage as IMarkupAttribute;
			if (markupAttr != null)
				return markupAttr.Value;

			return null;
		}

	}

}